<?php
/**
 * +---------------------------------------------------------------
 * | Author: 北京永青宇创科技有限公司
 * | Date: 2020/03/12
 * | 版本: 6.0
 * +---------------------------------------------------------------
 * | CopyRight: 北京永青宇创科技有限公司 All rights reserved.
 * +---------------------------------------------------------------
 * | 版权声明：云豹不是一个自由软件，是云豹官方推出的商业源码。
 * | 严禁在未经许可的情况下拷贝、复制、传播、使用云豹的任意代码
 * | 如有违反，请立即删除，否则您将面临承担相应，法律责任的风险。
 * | 如果需要取得官方授权，请联系官方 https://www.gepardshop.com
 * +---------------------------------------------------------------
 */
namespace app\survey\controller\admin;

use app\common\builder\FormBuilder;
use app\common\builder\SortBuilder;
use app\common\builder\ListBuilder;
use app\survey\model\SurveyTheme;

class Survey extends SurveyAdmin
{
    protected $Model;

    public function initialize()
    {
        parent::initialize();
        $this->Model = model('Survey');
    }

    public function Index($page = 1, $r = 20)
    {
		$map = [];
		$category_id = input('category_id');
        if(!empty($category_id)){
            $map['category_id']=$category_id;
		}
		$type_id = input('type_id');
        if(!empty($type_id)){
            $map['type_id']=$type_id;
        }
        //关键字搜索
        $keyword = input('keyword');
        if (!empty($keyword)) {
            $map['title'] = ['like', '%' . $keyword . '%'];
        }

        $status = input('status');
        if (!empty($status)) {
            $map['status'] = $status;
        }
        //时间搜索
        $start_time = input('create_time');
        if (!empty($start_time)) {
            $start_time_arr = explode('~',$start_time);
            list($start_one,$start_end)=\yunbao\time::getSomeday($start_time_arr[0]);
            list($end_one,$end_end)=\yunbao\time::getSomeday($start_time_arr[1]);
            $map['create_time']=['between',[$start_one,$end_end]];
        }

        list($list, $pagehtml) = $this->Model->where($map)->pagedata($r);



        //查询关联数据，此逻辑需要优化
        if (!empty($list)) {
            foreach ($list as &$item) {
                // $item['name'] = get_info_title('module/table', $item['id'], 'title', '不存在');
            }
        }
        $builder = new ListBuilder();

        //处理标题和按钮
        $builder->setMetaTitle('问卷管理')
		->addTopButton('addnew', ['href' => url_admin('edit',$map)])
        ->addTopButton('self', ['title' => '批量排序', 'href' => url_admin('nest', $map)])
        ->addTopButton('forbid', ['model' => 'survey/Survey'])
        ->addTopButton('recycle', ['model' => 'survey/Survey'])
                //->addTopButton('self', ['title' => '排序', 'href' => url_admin('nest', $map)])
                ->addSearchItem('status', 'select', '状态', '状态', ['1' => '正常', '0' => '已禁用', '-1' => '已删除'])
                ->addSearchItem('create_time', 'dateranger', '发布时间', '发布时间')
                ->addSearchItem('keyword', 'text', '关键字', '关键字')
                ->setTableDataList($list)
                ->setTableDataPage($pagehtml)
				->addRightButton('self', ['title' => '页面管理', 'href' => url_admin('survey/surveyPage/index', ['survey_id' => '__data_id__'])])
	        ->addRightButton('priview', ['name' => 'priview', 'title' => '预览', 'href' => url_admin('priview', ['id' => '__data_id__'])])
	        ->addRightButton('info', ['name' => 'info', 'title' => '发布', 'href' => url_admin('publish', ['id' => '__data_id__'])])
	        ->addRightButton('edit', ['href' => url_admin('edit', ['id' => '__data_id__'])])
                ->addRightButton('finaldelete', ['model' => 'survey/Survey']);

        //处理字段
                $builder->addTableColumn('id', '编号','id');
                $builder->addTableColumn('category_name', '分类id','foreign_id');
                $builder->addTableColumn('type_name', '类型id','foreign_id');
                $builder->addTableColumn('title', '标题','text');
	    $builder->addTableColumn('code', '发布码', 'text');
                // $builder->addTableColumn('content', '详细内容','editor');
                $builder->addTableColumn('status', '状态','toggle');
                // $builder->addTableColumn('sort', '排序','integer');
                $builder->addTableColumn('time_start', '开始时间','datetime');
                $builder->addTableColumn('time_end', '结束时间','datetime');
                // $builder->addTableColumn('create_time', '创建时间','datetime');
                // $builder->addTableColumn('update_time', '更新时间','datetime');
        
        $builder->addTableColumn('right_button', '操作', 'btn');

        return $builder->display();
    }

	public function priview($id)
	{
		$project = $this->Model->find($id);
		if(empty($project) || empty($project['code'])) {
			$this->error('项目不存在或未发布');
		}

		$url = url('survey/survey/index', ['code' => $project['code']]);
		$this->redirect($url);
	}

	public function init()
	{
		$list = model('survey/survey')->select();
		foreach($list as $item) {
			$uni_code     = $item['id'] . $item['time_start'] . $item['time_end'];
			$item['code'] = \yunbao\auth::user_md5($uni_code, config('data_auth_key'));
			$temp = [
				'id'=>$item['id'],
			    'code'=>$item['code']
			];
			$all[]=$temp;
		}
		model('survey/survey')->saveAll($all);
	}

	public function publish($id = 0)
	{
		$map = [];
		if(request()->isPost()) {
			$data = input('');
			//更新发布码
			if($data['status'] == 1) {
				$uni_code     = $data['id'] . $data['time_start'] . $data['time_end'];
				$data['code'] = \yunbao\auth::user_md5($uni_code, config('data_auth_key'));
			} else {
				$data['code'] = null;
			}

			if($id != 0) {
				if($this->Model->allowField(true)->save($data, ['id' => $id])) {
					$this->success('操作成功', url_admin('index', $map));
				} else {
					$this->error('操作失败');
				}
			} else {

				if($this->Model->allowField(true)->save($data)) {
					$this->success('操作成功', url_admin('index', $map));
				} else {
					$this->error('操作失败');
				}
			}
		} else {
			$builder = new FormBuilder();

			if($id != 0) {
				$info = $this->Model->find($id);
			} else {
				$info = $map;
			}

			//处理标题
			$title_info = $id > 0 ? '编辑' : '新增';
			$builder->setMetaTitle('展示项目' . $title_info)
			        ->setAlert('注意：问卷项目的起止时间可以为空，一旦修改了起止时间，将重新生成发布地址')
			        ->setPostUrl(url_admin('publish'))
			        ->setFormData($info);

			//处理字段
			$builder->addFormItem('id', 'hidden', '编号');
			$builder->addFormItem('title', 'static', '标题');
			$builder->addFormItem('status', 'radio', '状态', '', [1 => '发布', 0 => '不发布']);
			$builder->addFormItem('time_start', 'datetime', '开始时间');
			$builder->addFormItem('time_end', 'datetime', '结束时间');

			return $builder->setSubmitTitle('确认发布')->display();
		};
	}

	public function info($id = 0)
	{
        $map = [];
		$builder = new FormBuilder();

		if ($id != 0) {
			$info = $this->Model->find($id);
		} else {
			$info = $map;
		}

		//处理标题
		$builder->setMetaTitle('问卷')
		        ->setPostUrl(url_admin('edit'))
		        ->setTemplate('layout/ucenter/info')
		        ->setBuilder('info')
		        ->setFormData($info);

		//处理字段
				$builder->addFormItem('id', 'id', '编号');
				$builder->addFormItem('category_name', 'foreign_id', '分类id');
				$builder->addFormItem('type_name', 'foreign_id', '类型id');
				$builder->addFormItem('title', 'text', '标题');
				$builder->addFormItem('description', 'textarea', '简介');
				// $builder->addFormItem('content', 'editor', '详细内容');
				$builder->addFormItem('status', 'toggle', '状态');
				// $builder->addFormItem('sort', 'integer', '排序');
				$builder->addFormItem('time_start', 'datetime', '开始时间');
				$builder->addFormItem('time_end', 'datetime', '结束时间');
				// $builder->addFormItem('create_time', 'datetime', '创建时间');
				// $builder->addFormItem('update_time', 'datetime', '更新时间');
		
		return $builder->display();
	}

    public function edit($id = 0)
    {
		$map = [];
		$category_id = input('category_id');
        if(!empty($category_id)){
            $map['category_id']=$category_id;
		}
		$type_id = input('type_id');
        if(!empty($type_id)){
            $map['type_id']=$type_id;
        }
        if (request()->isPost()) {
            $data = input('');
            if ($id != 0) {
                if ($this->Model->allowField(true)->save($data, ['id' => $id])) {
                    $this->success('操作成功', url_admin('index',$map));
                } else {
                    $this->error('操作失败');
                }
            } else {

                if ($this->Model->allowField(true)->save($data)) {
                    $this->success('操作成功', url_admin('index',$map));
                } else {
                    $this->error('操作失败');
                }
            }
        } else {
            $builder = new FormBuilder();

            if ($id != 0) {
                $info = $this->Model->find($id);
            } else {
				$info = $map;
				$info['status']=1;
            }

            //处理标题
            $title_info = $id>0?'编辑':'新增';
            $builder->setMetaTitle('问卷'.$title_info)
                    ->setPostUrl(url_admin('edit'))
                    ->setFormData($info);

            //处理字段
						$builder->addFormItem('id', 'id', '编号');
						$builder->addFormItem('type_id', 'radio', '类型','',\yunbao\modelhelp::get_foreign_list('survey/surveyType'));
                        $builder->addFormItem('category_id', 'radio', '分类','',\yunbao\modelhelp::get_foreign_list('survey/surveyCategory'));
	        $builder->addFormItem('theme', 'radio', '风格', '', SurveyTheme::getThemeList());
						$builder->addFormItem('title', 'text', '标题');
						$builder->addFormItem('cover_id', 'picture', '图片');
                        // $builder->addFormItem('description', 'textarea', '简介');
                        $builder->addFormItem('content', 'editor', '详细内容');
                        $builder->addFormItem('status', 'toggle', '状态');
                        // $builder->addFormItem('sort', 'integer', '排序');
                        $builder->addFormItem('time_start', 'datetime', '开始时间');
                        $builder->addFormItem('time_end', 'datetime', '结束时间');
                        // $builder->addFormItem('create_time', 'datetime', '创建时间');
                        // $builder->addFormItem('update_time', 'datetime', '更新时间');
            
            return $builder->display();
        };
    }

    public function del($id = 0)
    {
        $id = array_unique((array)input('id', 0));

        if (empty($id)) {
            $this->error(lang('_ERROR_DATA_SELECT_') . lang('_EXCLAMATION_'));
        }

        $map = array('id' => array('in', $id));
        if ($this->Model->where($map)->delete()) {

            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }
}